﻿using CommonTools;
using CommonTools.Controls;
using Newtonsoft.Json;
using shop.Bll.cost;
using shop.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace shop.cost
{
    public class PostPriceBllUI: PostPriceBll
    {

        public override ControlBuilder GetUIBuilder()
        {
            return base.GetUIBuilder()
                .SetFlowBreak()
                .AddButton("导入旺店通资费", ImportData, false)
                .AddButton("检查没有登记的", CheckNoPrice, true)
                //.AddButton("配置资费策略", CheckNoPrice)
                ;
        }

        /// <summary> 找出没有登记资费的快递 </summary>
        public async Task<PageButtonResult> CheckNoPrice()
        {
            var list = await DB.FSql.Select<LogiInfo, PostPrice>()
                .LeftJoin((a, b) => a.logistics_name == b.logistics_name && b.isdel == false)
                .Where((a, b) => a.isdel == false)
                .Distinct()
                .ToListAsync((a, b) => new
                {
                    物流公司名称 = a.logistics_name,
                    快递老板 = a.LogiAcct,
                    是否代发 = a.IsAgent ? "是" : "否",
                    备注 = a.Remarks,
                });

            return new PageButtonResult(true, null,false, list);
        }

        /// <summary> 导入旺店通自费 </summary>
        public async Task<PageButtonResult> ImportData()
        {
            if (InputBox.GetValue<DateTime>("运费的起始日期",DateTime.Today,CN.systemInfo,out var begin ,"yyyy-MM-dd")
                ==false)
            {
                return new PageButtonResult(false);
            }

            var dt = ExcelHelper.Import();

            if (dt == null)
            {
                return new PageButtonResult(false);
            }

            // 特殊重量区间1	特殊区间1邮资	特殊重量区间2	特殊区间2邮资	特殊重量区间3	特殊区间3邮资	特殊重量区间4	特殊区间4邮资	特殊重量区间5	特殊区间5邮资	特殊重量区间6	特殊区间6邮资	特殊重量区间7	特殊区间7邮资	特殊重量区间8	特殊区间8邮资
            // 仓库或店铺	省份	城市	县区	物流公司	最优重量上限	特殊重量区间1	特殊区间1邮资	特殊重量区间2	特殊区间2邮资	特殊重量区间3	特殊区间3邮资	特殊重量区间4	特殊区间4邮资	特殊重量区间5	特殊区间5邮资	特殊重量区间6	特殊区间6邮资	特殊重量区间7	特殊区间7邮资	特殊重量区间8	特殊区间8邮资	首重	首重资费	重量区间1	续重单位1	单位资费1	重量区间2	续重单位2	单位资费2	重量区间3	续重单位3	单位资费3	重量区间4	续重单位4	单位资费4	取整方式	抛重比

            var list = dt.AsEnumerable()
                .Select(a=> ConvertToModel(a) )
                .ToList();

            var end = new DateTime(2099, 1, 1);
            var batch = DateTime.Now.ToString("yyyy-MM-ddTHHmmss") + Guid.NewGuid().ToString();


            var res = await WaitUI.RunAsync(async () =>
            {

                // 
                list = list.GroupBy(a=> new {a.logistics_name, a.SpecialRangeJson , a.CommonRangeJson , a.firstWeight, a.firstWeightPrice, a.roundMode, a.weightRatio, a.MinAmount})
                .Select(a=> new PostPrice()
                {
                    //shop_name=a.Key.shop_name,
                    logistics_name= a.Key.logistics_name,
                    provinceJson= a.Select(c=> c.provinceJson).Distinct().Aggregate((c,n)=> c+","+n),
                    StockJson = a.Select(c=> c.StockJson).Distinct().Aggregate((c,n)=> c+","+n),
                    SpecialRangeJson=a.Key.SpecialRangeJson,
                    CommonRangeJson=a.Key.CommonRangeJson,
                    firstWeight=a.Key.firstWeight,
                    firstWeightPrice=a.Key.firstWeightPrice,
                    MinAmount= a.Key.MinAmount,
                    roundMode=a.Key.roundMode,
                    weightRatio=a.Key.weightRatio,
                    BeginDate= begin,
                    EndDate= end,
                    batch = batch,
                } )
                .ToList();


                //将之前的日期改了 
                end = end.AddDays(-1);

                await DB.FSql.Update<PostPrice>()
                .Where(a => a.isdel == false && a.EndDate >= begin)
                .Set(a => a.EndDate, end)
                .ExecuteAffrowsAsync();

                await DB.FSql.Insert(list).ExecuteAffrowsAsync();
   


                //修改旧的日期  a是旧数据
                await DB.FSql.Update<PostPrice>()
                    .Join<PostPrice>((a, b) => a.logistics_name == b.logistics_name && a.provinceJson== b.provinceJson && a.Id != b.Id && b.batch == batch && (a.batch == null || a.batch== string.Empty || a.batch != batch))
                    .Set((a, b) => a.EndDate == b.BeginDate.Value.AddDays(-1))
                    .Where((a, b) => a.isdel == false && b.isdel == false && b.batch == batch && (a.batch == null || a.batch== string.Empty || a.batch != batch) && a.EndDate >= b.BeginDate)
                    .ExecuteAffrowsAsync();


                return list.Select(a => ToDto(a)).ToList();

            });


            return new PageButtonResult(true, null,true,  res);
        }


        private PostPrice ConvertToModel(DataRow row)
        {
            var model = new PostPrice()
            {
                provinceJson= row.Field<string>("省份"),
                logistics_name = row.Field<string>("物流公司"),
                StockJson = row.Field<string>("仓库"),
                firstWeight = row.Field<string>("首重").IsNull(0m),
                firstWeightPrice= row.Field<string>("首重资费").IsNull(0m),
                MinAmount = row.Field<string>("最低收费").IsNull(0m),
                roundMode = row.Field<string>("取整方式"),
                weightRatio = row.Field<string>("抛重比").IsNull(0m)
            };

            var rngs = new List<SpecialRange>();

            foreach (DataColumn item in row.Table.Columns)
            {
                if (item.ColumnName.StartsWith("特殊重量区间"))
                {
                    var newRng = new SpecialRange()
                    {
                        WeightRange = row[item.ColumnName]?.ToString().IsNull(0m) ?? 0m,
                        Price = row[item.Ordinal + 1]?.ToString().IsNull(0m) ?? 0m,
                    };
                    if (newRng.WeightRange !=0 || newRng.Price !=0)
                    {
                        rngs.Add(newRng);
                    }
                }
            }

            // 
            model.SpecialRangeJson = JsonConvert.SerializeObject(rngs);


            //重量区间1	续重单位1	单位资费1
            rngs = new List<SpecialRange>();

            foreach (DataColumn item in row.Table.Columns)
            {
                if (item.ColumnName.StartsWith("重量区间"))
                {
                    var newRng = new SpecialRange()
                    {
                        WeightRange = row[item.ColumnName]?.ToString().IsNull(0m) ?? 0m,
                        UnitWeight = row[item.Ordinal + 1]?.ToString().IsNull(0m) ?? 0m,
                        Price = row[item.Ordinal + 2]?.ToString().IsNull(0m) ?? 0m,
                    };
                    if (newRng.WeightRange !=0 || newRng.UnitWeight !=0 || newRng.Price !=0 )
                    {
                        rngs.Add(newRng);
                    }
                }
            }

            model.CommonRangeJson = JsonConvert.SerializeObject(rngs);


            return model;
        }



        /// <summary> 错误的日期改一下 </summary>
        public async Task Jiancha()
        {
            var list = await DB.FSql.Select<PostPrice>()
                .Where(a => a.isdel == false)
                .OrderBy(a=> a.logistics_name)
                .OrderBy(a=> a.provinceJson)
                .OrderByDescending(a=> a.BeginDate)
                .ToListAsync();


            foreach (var item in list)
            {
                var find = list.Where(a => a.logistics_name == item.logistics_name && a.provinceJson == item.provinceJson && a.Id != item.Id)
                    .Where(a => item.BeginDate < a.EndDate && item.BeginDate> a.BeginDate)
                    .OrderByDescending(a => a.BeginDate)
                    .FirstOrDefault();

                if (find != null)
                {
                    find.EndDate = item.BeginDate.Value.AddDays(-1);
                    //
                    await DB.FSql.Update<PostPrice>()
                        .Where(a => find.Id == a.Id)
                        .Set(a => a.EndDate, find.EndDate)
                        .ExecuteAffrowsAsync();
                    continue;
                }
            }
            
        }

    }




}
